package it.patamau.bukkit.afk;

import java.util.Collection;
import java.util.logging.Level;

import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;

/**
 * Handle events for all Player related events
 * such as commands
 * @author patamau
 */
public class AfkPlayerListener extends PlayerListener {
    private final AfkPlugin plugin;

    public AfkPlayerListener(AfkPlugin plugin) {
        this.plugin = plugin;
    }
    
    /*
    public void onPlayerJoin(PlayerEvent event){
    	Player p = event.getPlayer();
    	p.sendMessage("[Afk "+_plugin.getVersion()+"] type /afkhelp for available commands");
    }
    */
    
    public void onPlayerMove(PlayerMoveEvent event){
    	Player p = event.getPlayer();
    	//force the player to be removed from away status if it is in
    	plugin.setAfk(p, false, null);
    }
    
    public void onPlayerQuit(PlayerQuitEvent event){
    	Player p = event.getPlayer();
    	plugin.removePlayer(p);
    }
    
    public void onPlayerJoin(PlayerJoinEvent event){
    	Player p = event.getPlayer();
    	plugin.getPlayer(p.getName()); //creates the player if it doesn't exist already
    }
    
    public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)  {
    	Player player = event.getPlayer();
        String[] split = event.getMessage().split(" ");
        if(split.length<1) {
        	plugin.log(Level.WARNING,"command received, but no arguments are available: "+event.getMessage());
        	return; //XXX: is it possible?
        }
        String cmd = split[0];
        event.setCancelled(true); //prevent other plugins or the server to handle this
        if(cmd.equalsIgnoreCase("/afklist")){
        	Collection<String> aps = plugin.getAfkPlayers();
    		StringBuffer sb = new StringBuffer();
            for(String ap: aps){
            	sb.append(ap);
            	sb.append(" ");
            }
            if(aps.size()>0){
            	plugin.sendMessage("afk.player.list", "Players currently AFK {0}: {1}", player, Integer.toString(aps.size()), sb.toString());
            }else{
            	plugin.sendMessage("afk.player.nolist", "No players AFK", player);
            }
        }else if(cmd.equalsIgnoreCase("/afkstat")){
        	String p = null;
        	if(split.length>1){
        		p = split[1];
        	}
        	if(p==null){
        		plugin.sendMessage("afk.error.syntax", "Command error: {0}", player, "specify a player name");
        	}else{
        		Player sp = plugin.getServer().getPlayer(p);
        		if(sp!=null){
        			p = sp.getName();
		        	AfkPlayerStat pstat = plugin.getPlayer(p);
		        	long dt = (System.currentTimeMillis()-pstat.getTime())/60000;
		        	if(pstat.isAfk()){
		        		plugin.sendMessage("afk.player.stat", "{0} has been AFK for {1} minutes because {2}", player, pstat.getName(), dt, pstat.getReason());
		        	}else{
		        		plugin.sendMessage("afk.player.nostat", "{0} has been playing nonstop for the last {1} minutes ", player, pstat.getName(), dt);
		        	}
        		}else{
        			plugin.sendMessage("afk.error.generic", "{0}", player, "Wrong player name");
        		}
        	}
        }else if(cmd.equalsIgnoreCase("/afkhelp")){
        	//print a list of available commands
        	player.sendMessage("[Afk] command list:");
        	player.sendMessage(" /afklist: shows all the AFK players");
        	player.sendMessage(" /afkstat <player>: tells if the player is AFK and why");
        	player.sendMessage(" /afk [reason]: toggle your AFK status with an optional reason");
        }else if(cmd.equalsIgnoreCase("/afk")){
        	String r = null;
        	if(split.length>1){
        		StringBuffer sb = new StringBuffer();
        		for(int i=1; i<split.length; i++){
        			sb.append(split[i]);
        			if(i<(split.length-1)){
        				sb.append(" ");
        			}
        		}
        		r = sb.toString();
        	}
        	boolean afk=!plugin.isAfk(player.getName());
        	//force updating the reason setting afk to true even if it was already afk
        	//this will force the next call to update all the lists
        	if(r!=null){
        		afk=true;
        	}
        	//toggle afk status
        	plugin.setAfk(player, afk, r);
        }else{
        	//restore event if it cannot be handled by this plugin
        	event.setCancelled(false);
        }
    }
}
